<template>
  <a-layout id="layout">
    <!-- 头部导航，用于存放标签页 -->
    <a-layout-header class="head">
      <img class="logo" alt="DataStealer logo" src="../assets/DataStealer.png">
      <span>DataStealer</span>
      <div class="change-locale">
        <a-radio-group :default-value="zhCN" @change="changeLocale">
          <a-radio-button key="en" :value="null">
            English
          </a-radio-button>
          <a-radio-button key="cn" :value="zhCN">
            中文
          </a-radio-button>
        </a-radio-group>
      </div>
    </a-layout-header>

    <a-layout class="content">
      <a-locale-provider :locale="locale">
        <!-- 左边导航 -->
        <a-layout-sider class="sider" collapsible collapsedWidth="230" v-model="collapsed" :trigger="null" theme="light" width="330">
          <!-- 异步树作为菜单 -->
          <a-tree id="tree" class="menuTree" :style="{ color: '#000' }" showIcon :load-data="onLoadData" :tree-data="treeData" @expand="handleExpand" @select="handleSelect">
          </a-tree>
        </a-layout-sider>
      </a-locale-provider>

      <!-- 内容区域 -->
      <a-layout-content :style="{ padding: '24px', background: '#fff', minHeight: '280px' }">
        <transition name="slide-fade" mode="out-in">
          <router-view></router-view>
        </transition>
      </a-layout-content>
    </a-layout>
  </a-layout>
</template>

<script >
import zhCN from 'ant-design-vue/es/locale-provider/zh_CN';
import moment from 'moment';
import 'moment/locale/zh-cn';
import { getDataSource, getSchema, getTable } from '../api/requet.js'
export default {
  data() {
    return {
      locale: zhCN,
      zhCN,
      selectdMenu: "",
      // 折叠左边导航
      collapsed: true,
      // 初始化菜单数据
      treeData: [
        { title: this.$t('home.DashBoard'), key: 'DashBoard', isLeaf: true },
        { title: this.$t('home.CustomSql'), key: 'CustomSql', isLeaf: true },
        { title: this.$t('home.DataSource'), key: 'DataSource' }
      ]
    };
  },
  computed: {
    // 菜单初始化数据，加入computed节点，以便中英文切换时生效
    // treeData: {
    //   get: function () {
    //     return [
    //       { title: this.$t('home.DashBoard'), key: 'DashBoard', isLeaf: true },
    //       { title: this.$t('home.CustomSql'), key: 'CustomSql', isLeaf: true },
    //       { title: this.$t('home.DataSource'), key: 'DataSource' }]
    //   },
    //   set: function (newData) {
    //     console.log(newData)
    //     return newData;
    //   }
    // },
  },
  methods: {
    // 异步加载子节点，空方法，在其他方法处理
    onLoadData() {
      return new Promise(resolve => {
        resolve();
      });
    },
    // 获取数据源信息，存入session
    async getDataSourceInfo() {
      var data = await getDataSource();
      window.sessionStorage.setItem("db", data.databaseProductName);
      window.sessionStorage.setItem("dataSource", JSON.stringify(data));
    },
    // 处理点击DataSource
    async handleDataSource(node) {
      // 获取schema数据并加载到树
      var schemaList = await getSchema();
      node.dataRef.children = [];
      for (var schema of schemaList) {
        node.dataRef.children.push({
          key: 'Schema.' + schema.schemaName,
          title: schema.schemaName,
          isLeaf: false
        });
      }
      this.treeData = [...this.treeData];
    },
    // 处理点击Schema
    async handleSchema(schemaName, node) {
      // 获取schema下的table
      var tableList = await getTable(schemaName);
      // 存到session
      window.sessionStorage.setItem("tableList", JSON.stringify(tableList));
      // 加载到树
      node.dataRef.children = [];
      for (var table of tableList) {
        node.dataRef.children.push({
          key: 'Table.' + schemaName + '.' + table.tableName,
          title: table.tableName,
          isLeaf: true
        });
      }
      this.treeData = [...this.treeData];
      // 跳到对应页面
      this.$router.push({ path: '/schema', query: { schema: schemaName } });
    },
    // 处理点击Table
    async handleTable(tableName) {
      var index = tableName.indexOf('.');
      var schemaName = tableName.substring(0, index);
      tableName = tableName.substring(index + 1);
      this.$router.push({ path: '/table', query: { schema: schemaName, table: tableName } });
    },
    // 处理展开
    handleExpand(expandedKeys, { expanded, node }) {
      if (expanded) {
        if (expandedKeys.length == 1) {
          this.handleDataSource(node);
        } else if (expandedKeys.length == 2) {
          // 如果点击了schema，则展开菜单
          this.collapsed = false;
          // 获取当前schema下的表并显示
          this.handleSchema(expandedKeys[1].substring(7), node);
        }
      }
      if (!expanded && expandedKeys.length == 1) {
        // 如果是收缩到了第二层，则折叠菜单
        this.collapsed = true;
      }
    },
    // 处理点击
    handleSelect(selectedKeys, { node }) {
      if (selectedKeys.length == 1) {
        this.selectdMenu = selectedKeys[0];
      }
      if (this.selectdMenu === 'DashBoard') {
        // 点击了仪表盘
        this.$router.push("/dashBoard");
      } else if (this.selectdMenu === 'CustomSql') {
        // 点击了查询
        this.$router.push("/customSql");
      } else if (this.selectdMenu.indexOf('Schema.') != -1) {
        // 点击了数据源下的schema
        this.handleSchema(this.selectdMenu.substring(7), node);
      } else if (this.selectdMenu.indexOf('Table.') != -1) {
        // 点击了schema里面的表
        this.handleTable(this.selectdMenu.substring(6));
      }
    },
    changeLocale(e) {
      this.locale = e.target.value;
      if (!this.locale) {
        // 如果是空表示是英文
        moment.locale('en');
        this.$i18n.locale = 'en';
      } else {
        moment.locale('zh-cn');
        this.$i18n.locale = 'zh';
      }
    }
  },
  mounted() {
    this.getDataSourceInfo();
  }
};
</script>

<style>
#layout {
  height: 100%;
  background: #fff;
}
#layout .head {
  display: flex;
  height: 80px;
  padding: 10px;
  background: #fff;
  color: #000;
  display: flex;
  font-weight: bold;
  font-size: 24px;
  box-shadow: 0px 0px 5px 5px #f8f8f8;
  text-align: center;
}
#layout .logo {
  width: 50px;
  height: 50px;
  margin-right: 10px;
}
#layout .content {
  margin-top: 30px;
}
#layout .change-locale {
  margin-left: auto;
  margin-right: 10px;
}
#layout .sider {
  box-shadow: 1px 1px 1px 1px #f5f5f5;
  overflow: auto;
}
span.ant-tree-title {
  color: #4f4f4f;
}
.menuTree /deep/ span.ant-tree-title {
  font-size: 16px;
}
.menuTree /deep/ span.ant-tree-node-selected {
  background: transparent !important;
}
</style>